/**  
 * @date 2023-11-20 
 * @author Zhang Yu
 */
package com.springboot.template.controller;

import com.springboot.template.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.concurrent.TimeUnit;

/**  
 * @description: TODO
 */
@RestController
@RequestMapping("/test")
@Api(value = "测试接口", tags = {"测试接口"})
public class TestController {

	@Autowired
	TestService testService;

    @ApiOperation("测试")
	@GetMapping("/get")
	public String testRequest() {
		return testService.testRequest();
	}
    
    @ApiOperation("测试")
	@GetMapping("/get1")
    @ApiImplicitParams({
		@ApiImplicitParam(paramType="query", name="userId", dataType="String", required=true, value="用户Id")
	}) 
	@ApiResponses({
		@ApiResponse(code = 200, message = "请求成功"),
	}) 
	public String testRequestWithParam(@RequestParam String userId) {
		return "Hello GET";
	}


	@GetMapping("/stream")
	public ResponseEntity<StreamingResponseBody> streamData() {
		return ResponseEntity
				.status(HttpStatus.OK)
				.contentType(MediaType.APPLICATION_OCTET_STREAM)
				.body(outputStream -> {
					try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))) {
						// 模拟分步生成数据（例如 AI 推理过程）
						String[] steps = {"思考中...", "分析上下文...", "生成答案..."};

						for (String step : steps) {
							writer.write(step);
							writer.newLine();
							writer.flush(); // 刷新缓冲区，推送到前端
							TimeUnit.SECONDS.sleep(1); // 模拟计算时间
						}

						writer.write("最终答案：这是一个流式传输的 AI 回答示例！\n");
					} catch (IOException | InterruptedException e) {
						Thread.currentThread().interrupt();
					}
				});
	}

}
